package com.fenxiao.task.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.fenxiao.common.Pager;
import com.fenxiao.task.dao.TaskDao;
import com.fenxiao.task.entity.Task;
import com.fenxiao.user.entity.User;
import com.fenxiao.util.OrderNumber;

public class TaskDaoImpl implements TaskDao {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
/*@Override
public List<Task> getTaskAll(String openId,Integer taskStatus,Integer taskType) {
	// TODO Auto-generated method stub
	String hql="SELECT t FROM Task t where 1=1";*/
	
	/**
	  * 分页查询需求
	  */
	public Pager findTaskPage(int pageSize,int page,String search){
		//from Task t left join t.user u  where t.taskStatus=4;
		String hql="from Task t left join t.user u  where t.taskStatus=0";
//		if(search!=null&&!"".equals(search.trim())){
//			 hql+="and t.taskTitle like'%"+search+"%'";
//		 }
		if(search!=null&&!"".equals(search.trim())){
			hql+="and t.taskCode like'%"+search+"%'";
		}
		 hql+=" order by t.pubTime desc";
		 int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
	
	
	}
	/**
	    * 查询所有记录数
	    * @param hql 查询的条件
	    * @return 总记录数
	    */
		public int getAllRowCount(String hql) {
			Session session=sessionFactory.openSession();
			List list=null;
			try{
				Query query=session.createQuery(hql);
			
				list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list.size();
			
		}
		/**
	    * 分页查询
	    * @param hql 查询的条件
	    * @param offset 开始记录
	    * @param length 一次查询几条记录
	    * @return
	    */
		public List  queryForPage(String hql, int offset, int length) {
			Session session=sessionFactory.openSession();
			List  list=null;
			try{
				Query query=session.createQuery(hql);
				query.setFirstResult(offset);
	           query.setMaxResults(length);
	           list=query.list();
				
			}catch (RuntimeException e) {
			   throw e;
			}
			session.close();
			return list;
		}
	
		/**
		 * 更新
		 */
		public int updateTask(Task task){
			
		this.sessionFactory.getCurrentSession().update(task);
		
		return 1;
			
		}
		/**
		 * 查询详情
		 */
		public Task queryTaskInfo(long taskId){
			String hql="from Task t  where t.taskId="+taskId;
			Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
			Object obj=query.uniqueResult();
			if(obj!=null){
			  return (Task) obj;	
			}else{
				return null;
			}
		}
		/**
		 * 添加任务
		 */
		public int addTask(Task task){
			this.sessionFactory.getCurrentSession().save(task);
			return 1;
		}
		/**
		 * 批量删除
		 */
		public int deleteAllTask(String number){
			String hql="delete Task t where t.taskId in ("+number+")";
			Query query =this.sessionFactory.getCurrentSession().createQuery(hql);
			int i=query.executeUpdate();
			return i;
		}
		/**
		 * 删除
		 */
		public int deleteTask(long taskId){
			String hql="delete Task t where t.taskId ="+taskId;
			Query query =this.sessionFactory.getCurrentSession().createQuery(hql);
			int i=query.executeUpdate();
			return i;
		}
		/**
		  * 分页查询任务
		  */
	public Pager queryTaskPage(int pageSize,int page,String search){
		String hql="from Task t left join t.user u  where t.taskStatus=1";
		if(search!=null&&!"".equals(search.trim())){
			 hql+="and t.taskTitle like'%"+search+"%'";
		 }
		 hql+=" order by t.pubTime desc";
		 int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
		}
	/**
	  * 分页查询结束任务
	  */
	public Pager queryEndTaskPage(int pageSize,int page,String search){
		String hql="from Task t left join t.user u  where t.taskStatus=2";
		if(search!=null&&!"".equals(search.trim())){
			 hql+="and t.taskTitle like'%"+search+"%'";
		 }
		 hql+=" order by t.pubTime desc";
		 int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
	}
	/**
	 * 分页查询审核的app的任务
	 */
	public Pager queryAppTaskPage(int pageSize,int page,String search){
		String hql="from Task t left join t.user u  where t.taskType=2 and t.taskStatus=4";
		if(search!=null&&!"".equals(search.trim())){
			 hql+="and t.taskTitle like'%"+search+"%'";
		 }
		 hql+=" order by t.pubTime desc";
		 int allRow =this.getAllRowCount(hql);    //总记录数
	       int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	       final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	       final int length = pageSize;    //每页记录数
	       final int currentPage = Pager.countCurrentPage(page);
	       List list = this.queryForPage(hql,offset, length); //"一页"的记录
	       
	       
	     //把分页信息保存到Bean中
	       Pager pages = new Pager();
	       pages.setPageSize(pageSize);    
	       pages.setCurrentPage(currentPage);
	       pages.setAllRow(allRow);
	       pages.setTotalPage(totalPage);
	       pages.setList(list);
	       pages.init();
	       return pages;
		
		
	}
	@Override
	public List<Task> getTaskAll(User user,Integer taskStatus,Integer taskType) {
		// TODO Auto-generated method stub
		String hql="SELECT t FROM Task t where t.province='"+user.getProvince()+"' and t.area='"+user.getArea()+"' and t.taskStatus=1 or t.area='全国' and t.taskStatus=1 "+"ORDER BY t.taskBeginTime DESC";
		
		if(taskStatus!=null){
			String hql1=" and t.taskStatus="+taskStatus;
			hql=hql+hql1;
		}
		if(taskType!=null){
			String hql2=" and t.taskType="+taskType;
			hql=hql+hql2;
		}
		
		
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
//		Object obj=query.uniqueResult();
		List<Task> list=query.list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
		
	}

	@Override
	public Task queryTaskById(long taskId) {
		// TODO Auto-generated method stub
		String hql="from Task t where t.taskId="+taskId;
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Task task=(Task) query.uniqueResult();
		if(task!=null){
			return task;
		}else{
			return null;
		}
		
	}

	@Override
	public List<Task> getThoseTasksCompleted(long userId) {
		// TODO Auto-generated method stub
		String hql="select t from Task t where t.user.id="+userId+" and t.taskStatus=1";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		List<Task> list=query.list();
		if(list!=null){
			return list;
		}else{
			return null;
		}
	}

	@Override
	public int updateTaskById(long taskId,String appRegisterName) {
		// TODO Auto-generated method stub
		
		String hql="update Task t set t.appRegisterName='"+appRegisterName+"' ,t.taskStatus=4 where t.taskId="+taskId;
		
		return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
	}
	//需求列表
	public List<Task> queryTaskList(long userid){
	  String hql="from Task t where t.user.id="+userid+"order by t.pubTime desc";		
	 	return sessionFactory.getCurrentSession().createQuery(hql).list();
	  
		}
	//编码
	public String getTaskCode() {
		// TODO Auto-generated method stub
		String recomCode = OrderNumber.taskCodePrefix+OrderNumber.getFormatDate();
		String hql="select max(taskId) from Task";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		Object obj=query.uniqueResult();
		if(obj==null){
			long  obj0=1;
			String obj1=String.format("%08d", obj0);
			recomCode=recomCode+obj1;
			return recomCode;
		}else{
			String obj2=String.format("%08d", obj);
			String codes= obj2.substring(obj2.length()-8, obj2.length());
			 int codei = Integer.parseInt(codes)+1;
			return recomCode+String.format("%08d", codei);
		}
		
	}



@Override
public Task queryTaskByContent(String content,String fromUserName) {
	// TODO Auto-generated method stub
	String hql="select t from Task t where t.randomCode='"+content+"' and t.taskType=1 and t.originalID='"+fromUserName+"'";
	Query query=sessionFactory.getCurrentSession().createQuery(hql);
	Object obj=query.uniqueResult();
	if(obj!=null){
		return (Task) obj;
	}else{
		return null;	
	}
}

@Override
public int updateTaskByMessage(String content,String originalID) {
	// TODO Auto-generated method stub
	String hql="update Task t set t.taskRemainderNumber=t.taskRemainderNumber-1 where t.randomCode='"+content+"' and t.taskRemainderNumber>0 and t.originalID='"+originalID+"'";
	
	return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
}


@Override
public int updateTaskByMessage(long taskId,double taskBonus) {
	// TODO Auto-generated method stub
	String hql="update Task t set t.taskRemainderNumber=t.taskRemainderNumber-1,t.taskSBonus=t.taskSBonus-"+taskBonus+" where t.taskId="+taskId+" and t.taskRemainderNumber>0";
	return sessionFactory.getCurrentSession().createQuery(hql).executeUpdate();
 
}

private String Date() {
	// TODO Auto-generated method stub
	return null;
}
/**
 * 查询正在进行中的任务
 */
public List<Task> onTaskList(int taskType, int bounts,String area,User user){
	//from Task t WHERE  TO_DAYS(t.taskEndTime)>= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and  t.taskRemainderNumber>0
	String sql="from Task t WHERE  TO_DAYS(t.taskEndTime)>= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and  t.taskRemainderNumber>0 ";
	 if(taskType!=0){
		 sql+=" and t.taskType="+taskType;
	 }
	 if(area!=null&&!"".equals(area)){
		 sql+=" and t.area='"+area+"'";
	 }else{
		 sql+=" and t.area in('"+user.getArea()+"','全国')";
	 }
	 if(bounts==1){
		 sql+=" order by t.taskBonus  desc";
	 }else if(bounts==2){
		 sql+=" order by t.taskBonus  asc";
	 }else{
		 sql+=" order by t.taskBeginTime desc";
	 }
	 Query query=this.sessionFactory.getCurrentSession().createQuery(sql);
	 List<Task> list=query.list();
	 if(list.size()>0){
		 return list;
	 }else{
		return null; 
	 }
	 

}
/**
 * 分页查询任务
 */
public Pager queryTaskwc(User user,int pageSize,int page,String search){
	System.err.println("user+-----"+user.getArea());
//	String sql="from Task t WHERE  TO_DAYS(t.taskEndTime)>= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and  t.taskRemainderNumber>0 ";
String hql="select t from Task t  where t.area = '" + user.getArea() + "' and  TO_DAYS(t.taskEndTime)<= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and t.taskStatus=1 or t.area='全国' and TO_DAYS(t.taskEndTime)<= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and t.taskStatus=1 or t.area = '" + user.getArea() + "' and  t.taskRemainderNumber=0  and t.taskStatus=1 or t.area = '全国' and  t.taskRemainderNumber=0  and t.taskStatus=1";
if(search!=null&&!"".equals(search.trim())){
	 hql+="and t.taskTitle like'%"+search+"%'";
}
hql+=" order by t.pubTime desc";
int allRow =this.getAllRowCount(hql);    //总记录数
  int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
  final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
  final int length = pageSize;    //每页记录数
  final int currentPage = Pager.countCurrentPage(page);
  List list = this.queryForPage(hql,offset, length); //"一页"的记录
  
  
//把分页信息保存到Bean中
  Pager pages = new Pager();
  pages.setPageSize(pageSize);    
  pages.setCurrentPage(currentPage);
  pages.setAllRow(allRow);
  pages.setTotalPage(totalPage);
  pages.setList(list);
  pages.init();
  return pages;
}
//分页点亮查询
@Override
public Pager queryTaskdl(User user, int pageSize, int page, String search) {
	System.err.println("user+-----"+user.getArea());
//	String sql="from Task t WHERE  TO_DAYS(t.taskEndTime)>= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and  t.taskRemainderNumber>0 ";
String hql="select t from Task t  where t.province = '"+user.getProvince()+"' and t.area = '" + user.getArea() + "' and  t.taskEndTime> '"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "' and t.taskBeginTime < '"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "'  and t.taskRemainderNumber>0 and t.taskStatus=1 or t.province = '全国' and t.area='全国' and t.taskEndTime>'"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "' and t.taskBeginTime< '"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "'   and t.taskRemainderNumber>0 and t.taskStatus=1 ";
if(search!=null&&!"".equals(search.trim())){
	 hql+="and t.taskTitle like'%"+search+"%'";
}
hql+=" order by t.pubTime desc";
int allRow =this.getAllRowCount(hql);    //总记录数
  int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
  final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
  final int length = pageSize;    //每页记录数
  final int currentPage = Pager.countCurrentPage(page);
  List list = this.queryForPage(hql,offset, length); //"一页"的记录
  
  
//把分页信息保存到Bean中
  Pager pages = new Pager();
  pages.setPageSize(pageSize);    
  pages.setCurrentPage(currentPage);
  pages.setAllRow(allRow);
  pages.setTotalPage(totalPage);
  pages.setList(list);
  pages.init();
  return pages;
}

@Override
public Pager queryTaskStar(int pageSize, int page, String search,int taskType, int bounts,String area,User user) {
//	String sql="from Task t WHERE  TO_DAYS(t.taskEndTime)>= TO_DAYS('"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "') and  t.taskRemainderNumber>0 ";
String hql="select t from Task t  where t.taskEndTime> '"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "' and t.taskBeginTime < '"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "'  and  t.taskRemainderNumber>0 and t.taskStatus=1";
if(search!=null&&!"".equals(search.trim())){
	 hql+="and t.taskTitle like'%"+search+"%'";
}
if(taskType!=0){
	hql+=" and t.taskType="+taskType;
}
if(area!=null&&!"".equals(area)){
	hql+=" and t.area='"+area+"'";
}else{
	hql+=" and t.area in('"+user.getArea()+"','全国')";
}
if(bounts==1){
	hql+=" order by t.taskBonus  desc";
}else if(bounts==2){
	hql+=" order by t.taskBonus  asc";
}else{
	hql+=" order by t.taskBeginTime desc";
}
int allRow =this.getAllRowCount(hql);    //总记录数
  int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
  final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
  final int length = pageSize;    //每页记录数
  final int currentPage = Pager.countCurrentPage(page);
  List list = this.queryForPage(hql,offset, length); //"一页"的记录
  
  
//把分页信息保存到Bean中
  Pager pages = new Pager();
  pages.setPageSize(pageSize);    
  pages.setCurrentPage(currentPage);
  pages.setAllRow(allRow);
  pages.setTotalPage(totalPage);
  pages.setList(list);
  pages.init();
  return pages;
}
//分页修改需求页面
@Override
public Pager queryTaskxq(int pageSize, int page, long user) {
	 String hql="from Task t where t.user.id="+user+" order by t.pubTime desc";		
	 int allRow =this.getAllRowCount(hql);    //总记录数
	  int totalPage = Pager.countTotalPage(pageSize, allRow);    //总页数
	  final int offset = Pager.countOffset(pageSize, page);    //当前页开始记录
	  final int length = pageSize;    //每页记录数
	  final int currentPage = Pager.countCurrentPage(page);
	  List list = this.queryForPage(hql,offset, length); //"一页"的记录
	  
	  
	//把分页信息保存到Bean中
	  Pager pages = new Pager();
	  pages.setPageSize(pageSize);    
	  pages.setCurrentPage(currentPage);
	  pages.setAllRow(allRow);
	  pages.setTotalPage(totalPage);
	  pages.setList(list);
	  pages.init();
	  return pages;
}


}


